#!/usr/bin/perl -w
use strict;
use Includes;
use CGI qw/:standard *table *div -nosticky/;
use CGI::Pretty qw/ :html3 /;
use DBD::SQLite;

# Some variables
my $c = new CGI;
my $SUCCESS = 0;

# Some paths
my $chroot = ".inc/chroot";
my $path = "/usr/local/www/projects";

# Make the basic HTML and form 
print header(-type=>'text/html'),
			Includes::get_html("Project Descriptions"),
			div({id=>'main',class=>'rounded'},
					Includes::get_banner(),
					div({id=>'description'},
						&display(join("/",$path,$c->param('path')) || ''))),
			end_html();

# Check to see if we succeeded 
my $username = $c->cookie('username') || $c->param('username') || 'CHANGE_ME';
if($SUCCESS == 1 && $username  ne 'CHANGE_ME'){
	Includes::my_log('task4','info',"Completed by: %s",$username);
}

### Functions ###

sub display() {
	# The line at the end of /etc/passwd we are looking for
	my $match_line = "CONGRATULATIONS_YOU_HAVE_SOLVED_PUZZLE_4";
	my ($path,$retval,$matches) = (@_);
	# Make sure path is defined, if not, error out
	if($path){
		# Process the path and join it with the chroot
		my $file = join("/",$chroot,&process_path($path));
		if(-f $file){
			my @rows;
			open FILE,$file or $retval = "$!: $path";
			# Loop through each line of the file looking for the match
			while(<FILE>){
				$SUCCESS = 1 if(/$match_line/);
				push(@rows,td($_));
			}
			close FILE;
			$retval = table({id=>'results'},
					Tr([@rows]));
		}else{
			$retval = "$path is not a recognized file";
		}
	}else{
		$retval = "No path specified";
	}
	return $retval;
}

# Process the path
sub process_path(){
	my @path = split(/\//,shift);
	my @cur = qw();
	foreach(@path){
		if(/^\.\.$/){
			pop @cur;
		}else{
			push @cur,$_;
		}
	}
	return join("/",@cur);
}
